<?php

namespace App\Kuafu\Complain\Jobs;

use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Complain\Model\ComplainModel;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\Pay\Model\PayStreamModel;
use App\Library\FeiShu\SendFs;
use App\Remote\Feishu\Message\FeishuImageRemote;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Kuafu\GeneralFs\BuildFs;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use SplFileInfo;


class ComplainSubmitJob
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 队列名称
     *
     * @var string
     */
    public static string $QUEUE_NAME = '{RMS-COMPLAIN-SUBMIT-QUEUE}';


    public int $complainId;


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(int $complainId)
    {
        $this->complainId = $complainId;
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function handle()
    {
        $complainModel  = ComplainModel::query()->with("shopRel")->where("id", $this->complainId)->first();
        $orderSerialNum = '0';
        $field          = ['shopId', 'orderId', 'serialNum', 'createdAt', 'originalPrice'];
        $orderInfo      = OrderService::getOrderFieldByOrderId($complainModel->orderId, $field, $complainModel->shopId);
        $payStreamNo    = [];
        if ($orderInfo) {
            $payStreamNo    = PayStreamModel::suffix($complainModel->shopId)
                                            ->where('orderId', $complainModel->orderId)
                                            ->select("payNo")
                                            ->get()
                                            ->pluck("payNo")
                                            ->toArray();
            $orderSerialNum = str_pad($orderInfo['serialNum'], CodeEnum::ORDER_LEADING_ZERO, "0", STR_PAD_LEFT);
        }
        $payStreamNo    = implode(",", $payStreamNo);
        $noticeUrl      = CommonService::getComplainInfoWenAppUrl($this->complainId);//跳转到对应后台详情
        $originalImages = jsonToArr($complainModel->img, []);
        $newImages      = [];
        if ($originalImages) {
            $saveDir    = getTmpDir("/complain/" . formatDateYmd(time()));
            $fileSystem = getFileSystem();
            if (!$fileSystem->isDirectory($saveDir)) {
                $fileSystem->makeDirectory($saveDir, 0777, true);
            }

            $newImages = collect($originalImages)->map(function (string $img) use ($saveDir, $fileSystem) {
                if (!str_contains($img, "http",)) {
                    $img = config('other.IMAGE_URL') . 'applet-images/' . $img;
                }
                $filePath = vsprintf("%s/%s.%s", [
                    $saveDir,
                    md5($img),
                    (new SplFileInfo($img))->getExtension()
                ]);
                $fileSystem->put(
                    $filePath,
                    file_get_contents($img)
                );
                return FeishuImageRemote::uploadImage($filePath)["image_key"];
            })->values()->toArray();

        }

        if ($complainModel->orderId) {
            $templatePath = public_path("template/Complain/ComplainFsTemplate.blade.php");
            $params       = [
                "title"          => "小程序订单投诉通知" . '(' . $complainModel->shopRel->shopCode . '-' . $complainModel->reason . ')',
                "shopName"       => $complainModel->shopRel->shopCode . $complainModel->shopRel->name,
                "orderNo"        => $complainModel->orderId,
                "orderSerialNum" => $orderSerialNum,
                "phone"          => $complainModel->phone,
                "reason"         => $complainModel->reason,
                "payNo"          => $payStreamNo,
                "orderAmount"    => bcdiv100($orderInfo['originalPrice']) . "元",
                "desc"           => $complainModel->desc,
                "images"         => $newImages,
                "url"            => $noticeUrl
            ];
        } else {
            $templatePath = public_path("template/Complain/ComplainOutFsTemplate.blade.php");
            $params       = [
                "title"    => "小程序意见反馈通知" . '(' . $complainModel->shopRel->shopCode . '-' . $complainModel->reason . ')',
                "shopName" => $complainModel->shopRel->shopCode . $complainModel->shopRel->name,
                "phone"    => $complainModel->phone,
                "reason"   => $complainModel->reason,
                "desc"     => $complainModel->desc,
                "images"   => $newImages,
                "url"      => $noticeUrl
            ];
        }

        $templateJson = view()->file(
            $templatePath, $params
        )->render();

//        file_put_contents(storage_path("a.log"), $templateJson);

        BuildFs::newRobot(SendFs::ROBOT_APPLET_COMPLAIN, BuildFs::MSG_TYPE_CARD)
               ->setCardContent(json_decode(str_replace(["\n", "\r", "\r\n", PHP_EOL], "", $templateJson), true))
               ->send();
    }
}
